import { CHERRY_BLOSSOM } from './cherryBlossoms';
import { SnowFlake  } from './snowflake'
class Renderer{
    // 画布上下文对象
    context: any;
    INIT_CHERRY_BLOSSOM_COUNT = 30;
    MAX_ADDING_INTERVAL = 10;
    cherries: any[] = [];
    maxAddingInterval: any;
    addingInterval: any;
    // canvas 宽高
    width = window.innerWidth;
    height = 430;
    // 容器
    $container: HTMLDivElement | null;
    month: number = Number(new Date().getMonth);
    constructor(id: string) {
        this.$container = document.getElementById(id) as HTMLDivElement;
    }
	init(){
		this.setParameters();
		this.reconstructMethods();
		this.createCherries();
		this.render();
	}
	setParameters(){
        const canvas = document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;
        this.$container!.appendChild(canvas);
        this.context = canvas.getContext('2d');
		this.maxAddingInterval = Math.round(this.MAX_ADDING_INTERVAL * 1000 / this.width);
		this.addingInterval = this.maxAddingInterval;
	}
	reconstructMethods(){
		this.render = this.render.bind(this);
	}
	createCherries(){
		for(var i = 0, length = Math.round(this.INIT_CHERRY_BLOSSOM_COUNT * this.width / 1000); i < length; i++){
            if (this.month > 2 && this.month < 10) {
                this.cherries.push(new CHERRY_BLOSSOM(this, true));
            } else {
                this.cherries.push(new SnowFlake(this, true));
            }
		}
	}
	render(){
		requestAnimationFrame(this.render);
		this.context.clearRect(0, 0, this.width, this.height);
		this.cherries.sort(function(cherry1, cherry2){
			return cherry1.z - cherry2.z;
		});
		for(var i = this.cherries.length - 1; i >= 0; i--){
			if(!this.cherries[i].render(this.context)){
				this.cherries.splice(i, 1);
			}
		}
		if(--this.addingInterval == 0){
			this.addingInterval = this.maxAddingInterval;
            if (this.month > 2 && this.month < 10) {
                this.cherries.push(new CHERRY_BLOSSOM(this, true));
            } else {
                this.cherries.push(new SnowFlake(this, true));
            }
		}
	}
}

export default Renderer;